package com.dotstone.chipism.activity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.CodeInfo;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.ui.login.LoginActivity;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.NetUtil;
import com.dotstone.chipism.util.PhoneUtil;
import com.dotstone.chipism.util.QRCodeContentManager;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.StringUtil;
import com.dotstone.chipism.util.TimeUtils;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.view.BaseAnimatorSet;
import com.dotstone.chipism.view.NormalDialog;
import com.dotstone.chipism.view.OnBtnClickL;
import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class RegisterActivity1 extends BaseActivity {
	private LinearLayout mBackL;
	private TextView mTitleTv;
	private Button mSendTv;
	private Button mScanB;
	private EditText mTelEdit;
	private EditText mPasswordEdit;
	private EditText mPasswordEdit1;
	private EditText mVerificationEdit;
	private Button mRegisterBtn;
	private View mBlock;
	private String shareToken;
	private String userType;
	private String phone;
	private TextView mSpreadTv;
	private NormalDialog mNormalDialog;
	private BaseAnimatorSet bas_in;
	private BaseAnimatorSet bas_out;
	private SVProgressHUD mSVProgressHUD;
	private String openid;
	private TextView mCheckTv;
	private ImageView mCheckImg;
	private boolean check = false;
	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			Intent intent = new Intent(RegisterActivity1.this, LoginActivity.class);
			startActivity(intent);
			finish();
			break;
		case R.id.send_btn:
//			checkUsed();
			getVerificationCode();
			break;
		case R.id.register_btn:
			if (check) {
				if (NetUtil.isNetworkAvailable(RegisterActivity1.this)) {
					register();
				} else {
					ToastShow.Show(getApplicationContext(),
							getString(R.string.nonetwork));
				}
			} else {
				ToastShow.Show(getApplicationContext(), "请先同意用户注册使用协议");
			}
			break;
		case R.id.scan_btn:
			scan();
			break;
		case R.id.check_tv:
//			ToastShow.Show(getApplicationContext(), "尚待完善");
			Intent intent2 = new Intent(getApplicationContext(),TipActivity.class);
			startActivity(intent2);
			break;
		case R.id.check_img:
			if (check) {
				mCheckImg.setImageResource(R.drawable.gou12x);
			} else {
				mCheckImg.setImageResource(R.drawable.gou22x);
			}
			check = !check;
			break;
		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exit();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void exit() {
		Intent intent = new Intent(RegisterActivity1.this, LoginActivity.class);
		startActivity(intent);
		finish();
	}

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_register;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		userType = QRCodeContentManager.getInstance().getUserType();
		phone = QRCodeContentManager.getInstance().getPhone();
		shareToken = QRCodeContentManager.getInstance().getToken();
		if (phone != null) {
			mSpreadTv.setText(phone);
		} else {

		}
		QRCodeContentManager.getInstance().clear();
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		mBackL = $(R.id.back_layout);
		mTitleTv = $(R.id.title_tv);
		mTitleTv.setText(R.string.user_register);
		mSendTv = $(R.id.send_btn);
		mScanB = $(R.id.scan_btn);
		mTelEdit = $(R.id.tel_edit);
		mPasswordEdit = $(R.id.pwd_ed);
		mPasswordEdit1 = $(R.id.pwd_ed1);
		mVerificationEdit = $(R.id.check_edit);
		mRegisterBtn = $(R.id.register_btn);
		mSpreadTv = $(R.id.spread_tv);
		mBlock = (View) findViewById(R.id.block);
		mCheckTv = $(R.id.check_tv);
		mCheckImg = $(R.id.check_img);
		openid = getIntent().getStringExtra("openid");
		mSVProgressHUD = new SVProgressHUD(RegisterActivity1.this);
		mBackL.setOnClickListener(this);
		mSendTv.setOnClickListener(this);
		mScanB.setOnClickListener(this);
		mCheckImg.setOnClickListener(this);
		mCheckTv.setOnClickListener(this);
		mRegisterBtn.setOnClickListener(this);
		mTelEdit.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0, boolean hasFocus) {
				// TODO Auto-generated method stub
				if (hasFocus) {
					mTelEdit.setHint("");
				} else {
					if (mTelEdit.getText().toString().length() == 0) {
						mTelEdit.setHint(getString(R.string.phone_num));
					}
				}
			}
		});
		mPasswordEdit.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0, boolean hasFocus) {
				// TODO Auto-generated method stub
				if (hasFocus) {
					mPasswordEdit.setHint("");
				} else {
					if (mPasswordEdit.getText().toString().length() == 0) {
						mPasswordEdit.setHint(getString(R.string.pwd));
					}
				}
			}
		});
		mPasswordEdit1.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0, boolean hasFocus) {
				// TODO Auto-generated method stub
				if (hasFocus) {
					mPasswordEdit1.setHint("");
				} else {
					if (mPasswordEdit1.getText().toString().length() == 0) {
						mPasswordEdit1.setHint(getString(R.string.pwd1));
					}
				}
			}
		});
		mVerificationEdit.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0, boolean hasFocus) {
				// TODO Auto-generated method stub
				if (hasFocus) {
					mVerificationEdit.setHint("");
				} else {
					if (mVerificationEdit.getText().toString().length() == 0) {
						mVerificationEdit.setHint(getString(R.string.check));
					}
				}
			}
		});
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
			int statusBarHeight = getResources().getDimensionPixelSize(resourceId);
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
					statusBarHeight);
			mBlock.setLayoutParams(params);
		}
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	private void scan() {
		// Intent intent = new
		// Intent(RegisterActivity.this,CaptureActivity.class);
		// intent.putExtra("entry", 3);
		// startActivity(intent);
		if (Build.VERSION.SDK_INT >= 23) {
			if (ContextCompat.checkSelfPermission(getApplicationContext(),
					Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
				// 不能使用 调用以下方法申请摄像头权限
				boolean should = checkShould();
				if (should) {
					askPermission(Manifest.permission.CAMERA);
				} else {
				ActivityCompat.requestPermissions(RegisterActivity1.this, new String[] { Manifest.permission.CAMERA },
						0);
				}
			} else {
				Intent intent = new Intent(getApplicationContext(), CaptureActivity.class);
				intent.putExtra("entry", 3);
				startActivity(intent);
			}
		} else {
			Intent intent = new Intent(getApplicationContext(), CaptureActivity.class);
			intent.putExtra("entry", 3);
			startActivity(intent);
		}
	}
	
	@SuppressLint("NewApi")
	private boolean checkShould() {
		if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
			Log.e("wmy", "曾被设置永不提示");
			return true;
		} else {
			Log.e("wmy", "未曾设置永不提示");
			return false;
		}

	}

	private void askPermission(String permission) {
		String request = "";
		if (permission.equals(Manifest.permission.CAMERA)) {
			request = "摄像头权限被禁止，是否开启摄像头？";
		}
		mNormalDialog = new NormalDialog(RegisterActivity1.this);
		mNormalDialog.content(request).style(NormalDialog.STYLE_TWO)//
				.titleTextSize(18)//
				.showAnim(bas_in)//
				.dismissAnim(bas_out)//
				.show();
		mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
			}
		}, new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
				Intent localIntent = new Intent();
				localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
				localIntent.setData(Uri.fromParts("package", RegisterActivity1.this.getPackageName(), null));
				startActivity(localIntent);
			}
		});
	}
	
	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
		// TODO Auto-generated method stub
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		Log.i("wmy", "权限确认结果 requestCode = " + requestCode + " permissions [0] = " + permissions[0] + " grantResults[0]"
				+ grantResults[0]);
		switch (requestCode) {
		case 0:
			if (grantResults[0] == 0 && permissions[0].equals(Manifest.permission.CAMERA)) {
				Intent intent = new Intent(getApplicationContext(), CaptureActivity.class);
				intent.putExtra("entry", 3);
				startActivity(intent);
			} else {
				ToastShow.Show(getApplicationContext(), "您已禁止使用相机，无法使用扫一扫功能");
			}
			break;

		default:
			break;
		}
	}

	protected void checkUsed() {
		// 先正则判断 再发送
		if (NetUtil.isNetworkAvailable(this)) {
			String telNumber = mTelEdit.getText().toString().trim();
			if (TextUtils.isEmpty(telNumber)) {
				ToastShow.Show(getApplicationContext(), getString(R.string.phone_not_null));
				// mNoticeTv.setText(R.string.phone_not_null);
				return;
			}

			if (!PhoneUtil.isMobileNO(telNumber)) {
				ToastShow.Show(getApplicationContext(), getString(R.string.phone_not_right));
				return;
			}
			CodeInfo codeInfo = new CodeInfo();
			codeInfo.setKey("10000");
			codeInfo.setMobile(telNumber);
			codeInfo.setRequestTime(String.valueOf(System.currentTimeMillis()));
			Gson gson = new Gson();
			RequestParams params = new RequestParams(HttpURL.CHECK_PHONE);
			params.setBodyContent(gson.toJson(codeInfo));
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("Tag", "senCode=" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						int value = jsonObject.optInt("resultCode");
						if (value == 1) {
							boolean exist = jsonObject.getBoolean("data");
							if (exist) {
								getVerificationCode();
							} else {
								ToastShow.Show(getApplicationContext(), "该号码已经注册！");
							}
						} else if (value == 103) {
							ToastShow.Show(getApplicationContext(), getString(R.string.number_has_rogistered));
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}

				}

				@Override
				public void onError(Throwable ex, boolean isOnCallback) {
					Log.e("Tag", "onError" + ex.getMessage());
				}

				@Override
				public void onCancelled(CancelledException cex) {
					Log.e("Tag", "onCancelled");
				}

				@Override
				public void onFinished() {
					Log.e("Tag", "onFinished");
				}
			});
		} else {
			Toast toast = Toast.makeText(getApplicationContext(), R.string.nonetwork, Toast.LENGTH_SHORT);
			toast.show();
		}
	}

	/**
	 * 方法：login 用途：获取验证码后登录
	 */
	private void register() {
		if (NetUtil.isNetworkAvailable(this)) {
			final String phone = mTelEdit.getText().toString().trim();
			if (TextUtils.isEmpty(phone)) {
				Toast toast = Toast.makeText(getApplicationContext(), R.string.phone_not_null, Toast.LENGTH_SHORT);
				toast.show();
				return;
			}

			if (!PhoneUtil.isMobileNO(phone)) {
				Toast toast = Toast.makeText(getApplicationContext(), R.string.phone_not_right, Toast.LENGTH_SHORT);
				toast.show();
				return;
			}

			String code = mVerificationEdit.getText().toString().trim();
			if (TextUtils.isEmpty(code)) {
				Toast toast = Toast.makeText(getApplicationContext(), R.string.send_code_not_null, Toast.LENGTH_SHORT);
				toast.show();
				return;
			}
			final String pwd = mPasswordEdit.getText().toString().trim();
			if (TextUtils.isEmpty(pwd)) {
				Toast toast = Toast.makeText(getApplicationContext(), R.string.pwd_not_null, Toast.LENGTH_SHORT);
				toast.show();
				return;
			}

			if (pwd.length() < 6 || pwd.length() > 12) {
				Toast toast = Toast.makeText(getApplicationContext(), R.string.pwd_length_not_right,
						Toast.LENGTH_SHORT);
				toast.show();
				return;
			}

			if (StringUtil.isNumeric(pwd)) {
				Toast toast = Toast.makeText(getApplicationContext(), R.string.pwd_not_all_num, Toast.LENGTH_SHORT);
				toast.show();
				return;
			}

			if (StringUtil.isChar(pwd)) {
				Toast toast = Toast.makeText(getApplicationContext(), R.string.pwd_not_all_letter, Toast.LENGTH_SHORT);
				toast.show();
				return;
			}

			if (StringUtil.isConSpeCharacters(pwd)) {
				Toast toast = Toast.makeText(getApplicationContext(), R.string.pwd_not_all_character,
						Toast.LENGTH_SHORT);
				toast.show();
				return;
			}
			// ToastShow.Show(getApplicationContext(), HttpURL.REG_URL);
			mSVProgressHUD.showWithStatus("正在提交");
			RequestParams params = new RequestParams(HttpURL.REG_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("checkCode", code);
				obj.put("key", "10000");
				obj.put("mobile", phone);
				obj.put("password", pwd);
				obj.put("region", "86");
				obj.put("requestTime", System.currentTimeMillis() + "");
				obj.put("userName", phone);
				if (shareToken != null) {
					obj.put("shareToken", shareToken);
					obj.put("shartUserType", userType);
				}
				obj.put("weixinToken", openid);
				Log.d("test", "obj = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("test", "register=" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						String value = jsonObject.getString("resultCode");

						// 注册成功直接调用登录借口
						if (value.equals("1")) {
							login(phone, pwd);
						} else {
							String errorMsg = jsonObject.getString("errorMsg");
							Toast toast = Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_SHORT);
							toast.show();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onError(Throwable ex, boolean isOnCallback) {

				}

				@Override
				public void onCancelled(CancelledException cex) {
				}

				@Override
				public void onFinished() {
				}
			});
		} else {
			Toast toast = Toast.makeText(getApplicationContext(), R.string.nonetwork, Toast.LENGTH_SHORT);
			toast.show();
		}

	}

	private void getVerificationCode() {
		if (NetUtil.isNetworkAvailable(this)) {
			String phone = mTelEdit.getText().toString().trim();
			if (TextUtils.isEmpty(phone)) {
				Toast toast = Toast.makeText(getApplicationContext(), R.string.phone_not_null, Toast.LENGTH_SHORT);
				toast.show();
				return;
			}
			TimeUtils timeUtils = new TimeUtils(mSendTv, mSendTv.getText().toString());
			timeUtils.RunTimer();
			RequestParams params = new RequestParams(HttpURL.REG_CODE_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("codeType", "1");
				obj.put("key", "10000");
				obj.put("mobile", phone);
				obj.put("requestTime", "" + System.currentTimeMillis());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("test", "senCode=" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						int value = jsonObject.optInt("value");
						if (value == 100) {
							Toast toast = Toast.makeText(getApplicationContext(), R.string.send_code_success,
									Toast.LENGTH_SHORT);
							toast.show();
						} else if (value == 103) {
							Toast toast = Toast.makeText(getApplicationContext(), R.string.phone_has_register,
									Toast.LENGTH_SHORT);
							toast.show();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}

				}

				@Override
				public void onError(Throwable ex, boolean isOnCallback) {

				}

				@Override
				public void onCancelled(CancelledException cex) {
				}

				@Override
				public void onFinished() {
				}
			});
		} else {
			Toast toast = Toast.makeText(getApplicationContext(), R.string.nonetwork, Toast.LENGTH_SHORT);
			toast.show();
		}
	}

	private void login(final String name, final String pwd) {

		if (NetUtil.isNetworkAvailable(this)) {
			RequestParams params = new RequestParams(HttpURL.LOGIN_URL);
			params.setAsJsonContent(true);

			JSONObject obj = new JSONObject();
			try {
				obj.put("key", "10000");
				obj.put("mobile", name);
				obj.put("password", pwd);
				obj.put("reqAddress", "未知");
				obj.put("reqOs", "3");
				obj.put("requestTime", "" + System.currentTimeMillis());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());

			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("test", "login=" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);

						int resultCode = jsonObject.optInt("resultCode");
						MobclickAgent.onProfileSignIn(name);
						int user_id = jsonObject.getJSONObject("data").getJSONObject("userLogin").optInt("userId");
						String token = jsonObject.getJSONObject("data").getJSONObject("userLogin").optString("token");
						String password = jsonObject.getJSONObject("data").getJSONObject("userInfo").optString("password");
						SocketManager.getInstance().user_id = user_id + "";
						SocketManager.getInstance().token = token;
						SPUtils.put(RegisterActivity1.this, "user_id", user_id + "");
						try {
							String iconUrl = jsonObject.getJSONObject("data").getJSONObject("userInfo")
									.optString("iconUrl");
							String userName = jsonObject.getJSONObject("data").getJSONObject("userInfo")
									.optString("userName");
							SPUtils.put(RegisterActivity1.this, "iconUrl", iconUrl);
							SPUtils.put(RegisterActivity1.this, "userName", userName);
						} catch (Exception e) {

						}
						SPUtils.put(RegisterActivity1.this, "password", password);
						SPUtils.put(RegisterActivity1.this, "pwd", pwd);
						SPUtils.put(RegisterActivity1.this, "user_name", name);
						SPUtils.put(RegisterActivity1.this, "user_id", user_id + "");
						SPUtils.put(RegisterActivity1.this, "token", token);
						getShopToken();
						if (resultCode == 1) {
							// Intent intent = new Intent(RegisterActivity.this,
							// AddHouseActivity.class);
							// startActivity(intent);
							// finish();
							// 注册成功
							// 为用户添加默认的房屋 名字为“我的家”
							addDefaultHouse();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onError(Throwable ex, boolean isOnCallback) {

				}

				@Override
				public void onCancelled(CancelledException cex) {
				}

				@Override
				public void onFinished() {
				}
			});
		} else {
			Toast toast = Toast.makeText(getApplicationContext(), R.string.nonetwork, Toast.LENGTH_SHORT);
			toast.show();
		}

	}
	
	private void getShopToken(){
		RequestParams params = new RequestParams("http://api.shop.soochowlightpower.com/v2/xin.auth.signin");
//		params.addHeader("X-ECAPI-Authorization", (String) SPUtils.get(getApplicationContext(), "shopToken", ""));
		String user_name = (String)SPUtils.get(getApplicationContext(), "user_name", "");
		String password = (String)SPUtils.get(getApplicationContext(), "password", "");
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("username", user_name);
			obj.put("password", password);
			Log.e("wmy",
					" get ShopToken = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("wmy", "get ShopToken =" + result);
				JSONObject jsonObject;
				try {
					jsonObject = new JSONObject(result);
					JSONObject jo = jsonObject.getJSONObject("data");
					JSONObject userLogin = jo.getJSONObject("userLogin");
					String shopToken = userLogin.optString("token");
					Log.i("wmy", "shopToken = "+shopToken);
					SPUtils.put(getApplicationContext(), "shopToken", shopToken);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {
				Log.e("wmy", "get all dingdan cancel");
			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {
				// lt.error();
				Log.e("wmy", "get all dingdan error");
			}

			@Override
			public void onFinished() {
				Log.e("wmy", "get all dingdan finish");
			}
		});
	}

	private void addDefaultHouse() {
		RequestParams params = new RequestParams(HttpURL.HANDLE_HOME_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		String token = (String) SPUtils.get(getApplicationContext(), "token", "");
		try {
			obj.put("key", "10000");
			obj.put("homeName", "我的家");
			obj.put("handleType", "1");
			obj.put("token", token);
			obj.put("requestTime", "" + System.currentTimeMillis());
			Log.d("test", "login obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());

		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("Tag", "添加默认房间成功=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);

					int resultCode = jsonObject.optInt("resultCode");

					if (resultCode == 1) {
						// 上传成功后，获取家庭列表，如果返回的家庭列表只有一个 将其状态改为1 直接跳转至主界面
						getHouse();
					} else {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						String errorMsg = jsonObject.getString("errorMsg");
						ToastShow.Show(RegisterActivity1.this, errorMsg);
						throw new Exception();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				Log.e("Tag", "错误" + ex.getMessage());
			}

			@Override
			public void onCancelled(CancelledException cex) {

			}

			@Override
			public void onFinished() {
				Log.e("Tag", "完成");
			}
		});
	}

	private void getHouse() {
		RequestParams params = new RequestParams(HttpURL.GET_HOME_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("key", "10000");
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
			obj.put("requestTime", "" + System.currentTimeMillis());
			Log.d("test", "get house obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());

		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("Tag", "获取房间列表成功=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);

					int resultCode = jsonObject.optInt("resultCode");
					if (resultCode == 1) {
						JSONArray ja = jsonObject.optJSONArray("data");
						if (ja.length() > 0) {
							String hid = ja.getJSONObject(0).getString("hid");
							String homeName = ja.getJSONObject(0).getString("homeName");
							changeStatus(hid, homeName, 1);
						} else {
							ToastShow.Show(getApplicationContext(), "注册失败");
							if (mSVProgressHUD.isShowing()) {
								mSVProgressHUD.dismiss();
							}
						}
					} else {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						String errorMsg = jsonObject.getString("errorMsg");
						ToastShow.Show(getApplicationContext(), errorMsg);
						throw new Exception();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				Log.e("Tag", "错误" + ex.getMessage());
				// 清空所有本地数据，进入MainActivity
				if (mSVProgressHUD.isShowing()) {
					mSVProgressHUD.dismiss();
				}
				ToastShow.Show(getApplicationContext(), getString(R.string.failed));
			}

			@Override
			public void onCancelled(CancelledException cex) {

			}

			@Override
			public void onFinished() {
				Log.e("Tag", "完成");
			}
		});
	}

	private void changeStatus(final String hid, final String name, int status) {
		if (NetUtil.isNetworkAvailable(this)) {
			RequestParams params = new RequestParams(HttpURL.HANDLE_HOME_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			String token = (String) SPUtils.get(getApplicationContext(), "token", "");
			try {
				obj.put("hid", hid);
				obj.put("key", "10000");
				obj.put("homeName", name);
				obj.put("handleType", "2");
				obj.put("token", token);
				obj.put("status", status);
				obj.put("requestTime", "" + System.currentTimeMillis());
				Log.e("test", "更改房屋状态 = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());

			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("Tag", "成功=" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);

						int resultCode = jsonObject.optInt("resultCode");

						if (resultCode == 1) {
							if (mSVProgressHUD.isShowing()) {
								mSVProgressHUD.dismiss();
							}
							DeviceManager.getInstance().hid = hid;
							DeviceManager.getInstance().homeName = name;
							ToastShow.Show(getApplicationContext(), "注册成功！");
							Intent intent = new Intent(RegisterActivity1.this, MainActivity.class);
							startActivity(intent);
							finish();
						} else {
							if (mSVProgressHUD.isShowing()) {
								mSVProgressHUD.dismiss();
							}
							String errorMsg = jsonObject.getString("errorMsg");
							ToastShow.Show(RegisterActivity1.this, errorMsg);
							throw new Exception();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onError(Throwable ex, boolean isOnCallback) {
					if (mSVProgressHUD.isShowing()) {
						mSVProgressHUD.dismiss();
					}
					ToastShow.Show(getApplicationContext(), "网络错误！");
					Log.e("Tag", "错误" + ex.getMessage());
				}

				@Override
				public void onCancelled(CancelledException cex) {

				}

				@Override
				public void onFinished() {
					Log.e("Tag", "完成");
				}
			});
		} else {
			ToastShow.Show(getApplicationContext(), getString(R.string.nonetwork));
		}
	}

}
